package comp302.prototype.slide.handler;

import java.util.ArrayList;
import java.util.Iterator;

import comp302.prototype.component.Component;
import comp302.prototype.component.Line;
import comp302.prototype.component.Zigzag;
import comp302.prototype.xml.XMLNode;

public class ComponentHandler {
	private ArrayList<Component> components = new ArrayList<Component>();

	public void addComponent(Component component) {
		components.add(component);
	}

	public int componentCount() {
		return components.size();
	}

	public int indexOf(Component component) {
		return components.indexOf(component);
	}

	public Component componentAt(int index) {
		return components.get(index);
	}

	public void removeComponentAt(int index) {
		components.remove(index);
	}

	public void removeComponent(Component component) {
		components.remove(component);
	}

	public Iterator<Component> getIterator() {
		return components.iterator();
	}

	public void addComponentsToXML(XMLNode node) {
		Iterator<Component> iterator = components.iterator();

		while (iterator.hasNext()) {
			node.addChild(iterator.next().toXML());
		}
	}

	public void addComponentsFromXML(XMLNode node) {
		Iterator<XMLNode> iterator = node.childIterator();
		components = new ArrayList<Component>();

		while (iterator.hasNext()) {
			XMLNode componentXML = iterator.next();
			Component temp = null;

			if (componentXML.getName().equalsIgnoreCase("line")) {
				temp = new Line();
			} else if (componentXML.getName().equalsIgnoreCase("zigzag")) {
				temp = new Zigzag();
			}
			
			if (temp != null) {
				temp.fromXML(componentXML);
				components.add(temp);
			}
		}
	}
}
